package com.ken.astroboy.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RequestListener implements ServletRequestListener{
    
    private final Logger logger = LoggerFactory.getLogger("RequestListenner");

    //当用户请求到达、被初始化时触发该方法
    public void requestInitialized(ServletRequestEvent sre){
        
        HttpServletRequest request = (HttpServletRequest)sre.getServletRequest();
        HttpSession session = request.getSession();
        
        String page = request.getRequestURI();
                      
        if(!page.contains("/static/") &&  !page.contains("/robot/")){
            
            String sessionId = session.getId();       
            String ip = request.getRemoteAddr(); 
            String user = (String)session.getAttribute("user");
            
            user = (user == null) ? "游客" : user;

            StringBuilder sb = new StringBuilder();
            
            sb.append("User: [")
              .append(user)
              .append("] ")
              .append(" session id: [")
              .append(sessionId)
              .append("] visits ")
              .append(page)
              .append(" from ip ")
              .append(ip);
            
            logger.info(sb.toString());            
        }       
        
    }

    
    //当用户请求结束、被销毁时触发该方法
    public void requestDestroyed(ServletRequestEvent sre) {
    }
}

